package main.java.com.itlin.datastructure.blockingQueue;

import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 单锁实现
 * @param <E> - 元素类型
 */
public class BlockingQueue1<E> implements BlockingQueue<E> {

    private final E[] array;
    private int head;
    private int tail;
    private int size;


    @SuppressWarnings("all")
    public BlockingQueue1(int capacity) {
        array = (E[]) new Object[capacity];
    }

    private ReentrantLock lock = new ReentrantLock();
    private Condition headWaits = lock.newCondition();
    private Condition tailWaits = lock.newCondition();

    private boolean isEmpty() {
        return size == 0;
    }

    private boolean isFull() {
        return size == array.length;
    }
    @Override
    public void offer(E e) throws InterruptedException { // poll在 等待队列非空
        //加锁
        lock.lockInterruptibly();

        try{
            while (isFull()){
                tailWaits.await();
            }
            array[tail] = e;
            if(++tail == array.length){
                tail = 0;
            }
            size++;
            headWaits.signal(); // poll在等待 非空的线程开启
        }finally {
            lock.unlock();
        }
    }

    @Override
    public boolean offer(E e, long timeout) throws InterruptedException { // 毫秒  5s
        //加锁
        lock.lockInterruptibly();

        try{
            long t = TimeUnit.MILLISECONDS.toNanos(timeout);
            while (isFull()){
                if (t <= 0 ){
                    return false;
                }
                t = tailWaits.awaitNanos(t);//最多等待多少ns纳秒  1s  4s  返回值 返回等待的剩余时间
            }
            array[tail] = e;
            if(++tail == array.length){
                tail = 0;
            }
            size++;
            headWaits.signal(); // poll在等待 非空的线程开启
        }finally {
            lock.unlock();
        }
        return false;
    }

    @Override
    public E poll() throws InterruptedException {// offer 在 等待队列 非满

        //加锁
        lock.lockInterruptibly();
        try {
            while (isEmpty()){
                headWaits.await();
            }
            E e = array[head];
            array[head] = null;
            if (++head == array.length){
                head = 0;
            }
            size--;
            tailWaits.signal();// offer 等待 非满的线程开启
            return e;
        }finally {
            lock.unlock();
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BlockingQueue1<?> that = (BlockingQueue1<?>) o;
        return head == that.head && tail == that.tail && size == that.size && Arrays.equals(array, that.array) && Objects.equals(lock, that.lock) && Objects.equals(headWaits, that.headWaits) && Objects.equals(tailWaits, that.tailWaits);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(head, tail, size, lock, headWaits, tailWaits);
        result = 31 * result + Arrays.hashCode(array);
        return result;
    }

    @Override
    public String toString() {
        return "BlockingQueue1{" +
                "array=" + Arrays.toString(array) +
                '}';
    }

    public static void main(String[] args) throws InterruptedException {

        BlockingQueue1<String> queue = new BlockingQueue1<>(3);
        queue.offer("任务1");

        new Thread(() -> {
            try {
                queue.offer("任务2");
            }catch (InterruptedException e){
                throw new RuntimeException(e);
            }
        },"offer").start();

        new Thread(() -> {
            try {
                System.out.println(queue.poll());
            }catch (InterruptedException e){
                throw new RuntimeException(e);
            }
        },"poll").start();

    }
}
